package com.shujia.homework

import scala.io.Source

object Demo2Student {
  def main(args: Array[String]): Unit = {

    /**
     * 3、统计每科都及格的学生
     */
    //1、读取分数表
    val scoresList: List[(String, String, Int)] = Source
      .fromFile("data/score.txt")
      .getLines()
      .toList
      .map((line: String) => {
        val split: Array[String] = line.split(",")
        val id: String = split(0)
        val cid: String = split(1)
        val sco: Int = split(2).toInt
        (id, cid, sco)
      })

    //2、读取科目表
    val subjectList: List[(String, Int)] = Source
      .fromFile("data/subject.txt")
      .getLines()
      .toList
      .map((line: String) => {
        val split: Array[String] = line.split(",")
        val cid: String = split.head
        val sumSco: Int = split.last.toInt
        (cid, sumSco)
      })

    //将科目表转换成map集合，用于表join
    val subjectMap: Map[String, Int] = subjectList.toMap

    //关联分数表和科目表
    val joinList: List[(String, String, Int, Int)] = scoresList.map {
      case (id: String, cId: String, sco: Int) =>
        //通过科目表获取科目总分
        val sumSco: Int = subjectMap.getOrElse(cId, 0)
        //返回数据
        (id, cId, sco, sumSco)
    }

    //过滤掉所有不及格的分数
    val jigeLList: List[(String, String, Int, Int)] = joinList.filter {
      case (_: String, _: String, sco: Int, sumSco: Int) =>
        sco >= sumSco * 0.6
    }

    //按照学号分数，计算及格科目的数量
    val groupList: Map[String, List[(String, String, Int, Int)]] = jigeLList.groupBy {
      case (id: String, _: String, _: Int, _: Int) => id
    }

    //过滤掉没有都及格学生
    val filterList: Map[String, List[(String, String, Int, Int)]] = groupList.filter {
      case (_: String, scos: List[(String, String, Int, Int)]) =>
        scos.length == 6
    }

    //展开数据
    val resultList: List[(String, String, Int, Int)] = filterList
      .toList
      .flatMap {
        case (_: String, scos: List[(String, String, Int, Int)]) => scos
      }

    resultList.foreach(println)

  }

}
